const app = getApp();
const utils = require('../../utils/utils.js')
var aim = 1;
Page({
    data: {
        userinfo: {},
        longitude: 120.404556,
        latitude: 39.915156,
        scale: 16,
        seller_address: false, //商家信息是否出现
        markers: [],
        tel: '',
        isClick: true,
        nearySeller: [], //所有附近商家
        seller: {},
        isAuth: false,
        show_status: 0,
        inin_used_id: 0
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // 个人中心返回刷新页面
        // wx.showLoading({
        //     title: 'loading...',
        //     mask: true
        // });
        // let openid = app.globalData.openID;
        // if (openid != 'miand') {
            // 不存在openid，则用户未授权
            // 获取用户信息
            // this.getUseInfo();
            // 查询用户是否存在正在租借的订单
            // this.checkUsedStatus();
        // }
        // wx.hideLoading();
    },
    onLoad: function (options) {
        wx.showLoading({
            title: 'loading...',
            mask: true
        });
        let openid = app.globalData.openID;
        console.log("openid===>" + openid);
        let openid__ = wx.getStorageSync('openID');
        console.log("openid_缓存===>" + openid__);
        if (openid__) {
            openid = openid__;
            app.globalData.openID = openid__;
        }
        // if (openid != 'miand') {
        //     let scene = 100;
        //     this.userIsAuth(scene);
        // } else {
            // 获取用户授权code
            // this.getWxOpenidIndex();
        // }

        // 获取用户授权code
        this.getWxOpenidIndex(options);

        wx.hideLoading();
    },
    getSm: function (options) {
        var oq = options.q;
        // console.log(oq);
        if (oq != null && oq != "") {
            var url = decodeURIComponent(oq);
            var sn = url.split('/').pop() + "";
            app.globalData.deviceSn = sn;
            let deviceSn = app.globalData.deviceSn;
            if (deviceSn) {
                // 存在公共的设备SN，那么用户是扫码租借进入
                app.globalData.deviceSn = "";
                this.checkDeviceType(deviceSn);
            } else {
                this.getUseInfo();
            }
        } else {
            this.getUseInfo();
        }
    },
    getWxOpenidIndex(options) {
        let that = this;
        wx.login({
            success(res) {
                if (res.code) {
                    utils.httpRequest('/login', {
                        code: res.code
                    }, function (res) {
                        if (res.data.openid) {
                            wx.setStorageSync("openID", res.data.openid);
                            app.globalData.openID = res.data.openid;

                            // 扫码进去小程序，获取机柜SN
                            that.getSm(options);
                        }
                    })
                }
            }
        })
    },
    // ======================== 查询租借中的订单 start ===========================
    checkUsedStatus: function () {
        let that = this;
        wx.showLoading({
            title: 'loading...',
            mask: true
        })
        utils.httpRequest('/checkUsedStatus', {}, function (res) {
            if (res.code == 1) {
                wx.hideLoading();
                var used_id = res.data.used_id;
                var show_status = res.data.show_status;
                // show_status = 1;
                if (used_id == null || used_id == "") {
                    used_id = 0;
                    that.setData({
                        show_status: show_status,
                        inin_used_id: used_id
                    })
                } else {
                    // 存在使用记录
                    that.setData({
                        show_status: show_status,
                        inin_used_id: used_id,
                    })
                }

            }
        })
    },
    // 宝未弹出
    mybaodont: function () {
        var that = this
        wx.navigateTo({
            url: '/pages/testingUsed/testingUsed?used_id=' + that.data.inin_used_id
        })
    },
    //我已归还
    myoverdd: function () {
        var that = this
        wx.navigateTo({
            url: '/pages/testingUsed/testingUsed?used_id=' + that.data.inin_used_id
        })
    },
    // ======================== 查询租借中的订单 end ===========================
    // ================== 获取用户授权code =======================
    getWxOpenid: function () {
        let that = this;
        wx.login({
            success(res) {
                if (res.code) {
                    utils.httpRequest('/login', {
                        code: res.code
                    }, function (res) {
                        if (res.data.openid) {
                            wx.setStorageSync("openID", res.data.openid);
                            app.globalData.openID = res.data.openid;
                            // 查看用户是否授权
                            let scene = 100;
                            that.userIsAuth(scene);
                        } else {
                            if (aim < 3) {
                                wx.showToast({
                                    title: 'openID获取失败',
                                    duration: 2000,
                                    icon: 'none'
                                })
                                that.getWxOpenid();
                            } else {
                                wx.showModal({
                                    title: '温馨提示',
                                    content: '您点击了拒绝登录，将无法进入小程序，请登录之后再进入!!!',
                                    showCancel: false,
                                    confirmText: '返回登录',
                                    success: function (res) {
                                        if (res.confirm) {

                                        }
                                    }
                                })
                                return
                            }
                            aim++;
                        }
                    })
                }
            }
        })
    },
    // ===================== 判断用户是否授权 =============================
    userIsAuth(scene) {
        let that = this;
        let isAuth = this.data.isAuth;
        utils.httpRequest('/checkAuth', {}, function (res) {
            // console.log("scene-->" + scene);
            // console.log("userIsAuth-->" + JSON.stringify(res));
            if (res.code == 1) {
                if (res.data.is_auth == 1) { //已授权
                    that.getUseInfo();
                    if (scene == 1) {
                        //跳转用户界面
                        wx.navigateTo({
                            url: '../user/user'
                        });
                    }
                } else {
                    // 未获取到用户昵称信息，需要让用户再次授权
                    if (scene == 1) {
                        wx.navigateTo({
                            url: '../authorization/authorization?scene=1'
                        });
                    } else if (scene == 100) {
                        // console.log("userIsAuth---->跳转页面");
                        wx.navigateTo({
                            url: '../authorization/authorization?scene=100'
                        });
                    }
                }
            }
        })
    },


    // =========== 校验设备类型 ===============
    checkDeviceType: function (sn) {
        wx.showLoading({
            title: 'loading...',
            mask: true
        });
        let that = this;
        utils.httpRequest('/checkDeviceType', {
            sn: sn
        }, function (res) {
            wx.hideLoading();
            if (res.code == 1) {
                switch (res.data.type) {
                    case 0:
                        // 机柜设备租借
                        that.borrowDevice(sn);
                        break;
                    case 1:
                        // 充电线租借
                        that.lineBorrow(sn);
                        break;
                    default:
                        break;
                }
            }
        })
    },

    // ============ 获取用户信息 ================
    getUseInfo: function () {
        wx.showLoading({
            title: 'loading...',
            mask: true
        });
        let that = this;
        utils.httpRequest('/getInfo', {}, function (res) {
            wx.hideLoading();
            if (res.code == 1) {
                that.setData({
                    userinfo: res.data.user
                })
                // 开始获取定位信息
                that.getLocation();
            }
        })
    },
    // ============= 获取用户定位 ===============
    getLocation: function () {
        wx.showLoading({
            title: 'loading...',
            mask: true
        });
        let that = this;
        wx.getLocation({
            type: 'gcj02',
            success: (res) => {
                wx.hideLoading();
                that.setData({
                    longitude: res.longitude,
                    latitude: res.latitude
                })
                app.globalData.longitude = res.longitude;
                app.globalData.latitude = res.latitude;
                // 获取附近的商家
                that.getNearyShopInfo(res.longitude, res.latitude);
            },
            fail: (res) => {
                wx.hideLoading();
                wx.showToast({
                    title: "您的定位没有打开，请打开哦",
                    icon: 'none',
                    duration: 2000
                });
            }
        })
    },
    // ===========  获取附近的商家信息 ======================
    getNearyShopInfo: function (longitude, latitude) {
        wx.showLoading({
            title: 'loading...',
            mask: true
        });
        let that = this;
        utils.httpRequest('/getShopList', {
            longitude: longitude,
            latitude: latitude,
            isList: 0
        }, function (res) {
            wx.hideLoading();
            if (res.code == 1) {
                let arr = [];
                let nearySeller = [];
                if (res.data.list != null) {
                    let i = 0;
                    for (let s of res.data.list) {
                        i++;
                        nearySeller.push({
                            id: s.id,
                            sortId: i,
                            doorPhoto: s.doorPhoto,
                            storeName: s.storeName,
                            detailAddress: s.detailAddress,
                            inStock: s.inStock,
                            notInStock: s.notInStock,
                            distance: s.distance
                        });
                        arr.push({
                            id: i,
                            width: s.width,
                            height: s.height,
                            longitude: s.longitude,
                            latitude: s.latitude,
                            iconPath:"https://www.zjsuichong.com/min/images/dianc.png"
                        })
                    }
                }
                that.setData({
                    nearySeller: nearySeller
                })
                that.setData({
                    markers: arr
                })
            }
        })
    },
    // ==================== 搜索附近充电宝 ==============================
    searchAddress: function () {
        let that = this;
        wx.chooseLocation({
            success: function (res) {
                that.setData({
                    longitude: res.longitude,
                    latitude: res.latitude
                })
                app.globalData.longitude = res.longitude;
                app.globalData.latitude = res.latitude;
            }
        });
    },
    // ==================== 重置定位 ==============================
    toReset() {
        var that = this;
        wx.getLocation({
            type: 'gcj02',
            success: function (res) {
                let latitude = res.latitude
                let longitude = res.longitude
                that.setData({
                    latitude: latitude,
                    longitude: longitude,
                })
                // 获取附近的商家
                that.getNearyShopInfo(res.longitude, res.latitude);
            }
        })
        //调回缩放比，提升体验
        var promise = new Promise((resolve) => {
            that.mapCtx.moveToLocation();
            resolve('调回缩放比')
        })
        promise.then((value) => {
            setTimeout(() => {
                this.setData({
                    scale: 16
                })
            }, 1000)
        })
    },

    // =================== 点击商家所在位置 =======================
    markertaps(e) {
        let that = this;
        that.setData({
            seller_address: true
        })
        console.log("e->" + JSON.stringify(e));
        for (let s of that.data.nearySeller) {
            if (s.sortId == e.detail.markerId) {
                that.setData({
                    seller: s
                })
                return
            }
        }
    },
    // =================== 隐藏商家信息 ===================================
    hideSeller() {
        this.setData({
            seller_address: false
        })
    },
    //  ==================== 点击查看附近商家信息 ================================
    goNearbyShops() {
        let that = this;
        // 隐藏商家信息
        that.hideSeller();
        let dat = {
            longitude: that.data.longitude, //经度
            latitude: that.data.latitude // 纬度
        };
        wx.navigateTo({
            //跳转附近商家界面
            url: '../nearby/nearby?localtion=' + JSON.stringify(dat)
        });
    },
    // =================== 地图上弹出商家信息 ================
    goToShop() {
        let that = this;
        wx.navigateTo({
            url: '../shop/shop?id=' + that.data.seller.id
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        // 页面加载完成
        this.mapCtx = wx.createMapContext('myMap');
    },

    goToHelp() {
        //隐藏商家信息
        this.hideSeller();
        //跳转帮助页面
        wx.navigateTo({
            url: '../help/help'
        });
    },

    goToUser() {
        //隐藏商家信息
        this.hideSeller();
        let openid = app.globalData.openID;
        if (openid != 'miand') {
            // 跳转到个人中心
            let scene = 1;
            this.userIsAuth(scene);
        } else {
            // 未授权，跳转到授权页面
            wx.navigateTo({
                url: '../authorization/authorization?scene=1'
            });
        }
        // wx.navigateTo({
        //   url: '../borrow/borrow'
        // });
        // wx.navigateTo({
        //   url: '../linePassword/linePassword'
        // });
        // wx.navigateTo({
        //   url: '../borrowStatus/borrowStatus'
        // });
    },
    // ============= 扫码租借 =================
    toScan() {
        //调用二维码扫码功能
        let that = this;
        if (that.data.isClick) {
            that.setData({
                isClick: false
            })
            // 只允许从相机扫码
            wx.scanCode({
                onlyFromCamera: true,
                success(res) {
                    if (res.result) {
                        let sn = res.result.split('/').pop();
                        wx.showLoading({
                            title: 'loading...',
                            mask: true
                        })
                        utils.httpRequest('/checkDeviceType', {
                            sn: sn
                        }, function (res) {
                            wx.hideLoading();
                            if (res.code == 1) {
                                switch (res.data.type) {
                                    case 0:
                                        // 机柜设备租借
                                        that.borrowDevice(sn);
                                        break;
                                    case 1:
                                        // 充电线租借
                                        that.lineBorrow(sn);
                                        break;
                                    default:
                                        break;
                                }
                            }
                        })
                    } else {
                        wx.showToast({
                            title: "扫码失败",
                            icon: 'none',
                            duration: 2000
                        });
                    }
                },
                complete: function () {
                    that.setData({
                        isClick: true
                    })
                }
            })

        }
    },

    // ============================ 扫码租借机柜设备(第一步骤) ==============================
    borrowDevice(sn) {
        wx.showLoading({
            title: 'loading...',
            mask: true
        });
        utils.httpRequest('/deviceFirstStep', {
            sn: sn
        }, function (res) {
            wx.hideLoading();
            switch (res.code) {
                case 1:
                    // 跳转到租借充电宝界面
                    wx.navigateTo({
                        url: '../borrow/borrow?data=' + JSON.stringify(res.data)
                    });
                    break;
                default:
                    wx.showToast({
                        title: res.msg,
                        icon: 'none',
                        duration: 2000
                    });
                    break;
            }
        })
    },
    // ================================= 扫码租赁密码线 ================================
    lineBorrow(sn) {
        wx.showLoading({
            title: 'loading...',
            mask: true
        });
        utils.httpRequest('/lineScan', {
            sn: sn
        }, function (res) {
            wx.hideLoading();
            switch (res.code) {
                case 1:
                    // 租借
                    wx.navigateTo({
                        url: '../lineBorrow/lineBorrow?data=' + JSON.stringify(res.data)
                    })
                    break;
                case 2:
                    // 充电线已有订单
                    wx.navigateTo({
                        url: '../linePassword/linePassword?data=' + JSON.stringify(res.data)
                    })
                    break;
                case 3:
                    // 免费用户租借充电线，默认套餐1
                    wx.navigateTo({
                        url: '../linePassword/linePassword?data=' + JSON.stringify(res.data)
                    });
                    break;
                default:
                    wx.showToast({
                        title: res.msg,
                        icon: 'none',
                        duration: 2000
                    });
                    break;
            }
        })
    },

    // 视野发生变化时触发，
    regionchange(e) {
        var that = this;
        // 地图发生变化的时候，获取中间点，也就是用户选择的位置toFixed
        if (e.type == 'end') {
            this.mapCtx.getCenterLocation({
                type: 'gcj02',
                success: function (res) {
                    that.getNearyShopInfo(res.longitude, res.latitude);
                }
            })
        }
    },
});